<template>
  <div class="app-container">
    <div class="search-container">
      <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
        <el-form-item label="系统消息类型" prop="sysMessageType">
          <el-select v-model="queryParams.sysMessageType" class="width-120" clearable placeholder="请选择系统消息类型">
            <el-option
              v-for="dict in dictDataMap['system_message_type']"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否已读" prop="isSendOk">
          <el-select v-model="queryParams.isSendOk" class="width-120" clearable placeholder="请选择">
            <el-option
              v-for="dict in dictDataMap['sys_yes_no']"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="指定审核人" prop="designatedReviewer">
          <el-input
            v-model="queryParams.designatedReviewer"
            clearable
            placeholder="请输入指定审核人"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="指定审核科室" prop="designatedReviewDept">
          <el-input
            v-model="queryParams.designatedReviewDept"
            clearable
            placeholder="请输入指定审核科室"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="消息标题" prop="messageTitle">
          <el-input
            v-model="queryParams.messageTitle"
            clearable
            placeholder="请输入消息标题"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['system:sysMessage:add']"
          plain
          type="primary"
          @click="handleAdd"
        >
          <template
            #icon>
            <i-ep-plus/>
          </template>
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['system:sysMessage:edit']"
          :disabled="single"
          plain
          type="success"
          @click="handleUpdate"
        >
          <template #icon>
            <i-ep-edit/>
          </template>
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['system:sysMessage:remove']"
          :disabled="multiple"
          plain
          type="danger"
          @click="handleDelete"
        >
          <template #icon>
            <i-ep-delete/>
          </template>
          删除
        </el-button>
      </el-col>
    </el-row>

    <el-table v-adaptive :border="true" :data="sysMessageList" :header-cell-style="$headerCellStyle"
              :stripe="true" highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column :align="'center'" type="selection" width="55"/>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" header-align="center" label="消息标题" min-width="100"
                       prop="messageTitle"/>
      <el-table-column :align="'center'" label="系统消息类型" prop="sysMessageTypeName" width="100">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['system_message_type']" :value="scope.row.sysMessageType"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="消息内容" prop="messageContent"
                       width="100px">
        <template #default="scope">
          <el-popover
            :width="600"
            popper-style="height: 50%;overflow: auto;"
            placement="right"
            title="消息内容详情"
            trigger="hover"
          >
            <template #reference>
              <el-button type="primary">详情</el-button>
            </template>
            <span v-html="scope.row.messageContent"></span>
          </el-popover>

        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="是否发布" prop="isSendOk" width="80">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.isSendOk"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="发布人" prop="createByName" width="120"/>
      <el-table-column :align="'center'" label="发布时间" prop="sendTime" width="130"/>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" header-align="center" label="指定审核人"
                       prop="designatedReviewerName"/>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" header-align="center" label="指定审核科室"
                       prop="designatedReviewDeptName"/>
      <el-table-column :align="'center'" label="创建时间" prop="createTime" width="130"/>
      <el-table-column :align="'left'" class-name="small-padding fixed-width" header-align="center" label="操作"
                       width="115">
        <template #default="scope">
          <el-tooltip class="item" content="发布" effect="dark" placement="left">
            <el-button v-if="scope.row.isSendOk ==='N'" circle
                       type="primary"
                       @click="sendOkFun(scope.row)"
            >
              <template #icon>
                <svg-icon icon-class="guide"/>
              </template>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" content="修改" effect="dark" placement="top">
            <el-button v-if="scope.row.isSendOk ==='N'" v-hasPerm="['system:sysMessage:edit']"
                       circle
                       type="success"
                       @click="handleUpdate(scope.row)"
            >
              <template #icon>
                <i-ep-edit/>
              </template>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" content="删除" effect="dark" placement="top">
            <el-button v-if="scope.row.isSendOk ==='N'" v-hasPerm="['system:sysMessage:remove']"
                       circle
                       type="danger"
                       @click="handleDelete(scope.row)"
            >
              <template #icon>
                <i-ep-delete/>
              </template>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改系统消息字典对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="60%">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="系统消息类型" prop="sysMessageType">
          <el-select v-model="form.sysMessageType" placeholder="请选择系统消息类型">
            <el-option
              v-for="dict in dictDataMap['system_message_type']"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消息标题" prop="messageTitle">
          <el-input v-model="form.messageTitle" placeholder="请输入消息标题"/>
        </el-form-item>
        <el-form-item label="消息内容">
          <quill-editor ref="quillEditorRef" v-model="form.messageContent" @content-change="messageContentChange"/>
        </el-form-item>
        <el-form-item label="是否发布">
          <el-radio-group v-model="form.isSendOk">
            <el-radio
              v-for="dict in dictDataMap['sys_yes_no']"
              :key="dict.dictValue"
              :value="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="指定审核科室" prop="designatedReviewDept">
          <el-select v-model="form.designatedReviewDeptArray" :multiple="multiple" :placeholder="'请选择'" clearable
                     filterable
                     style="width: 100%;" @change="orgDeptGroupChange">
            <el-option v-for="item in orgDeptGroupList" :key="item.deptGroupId" :label="item.deptGroupName"
                       :value="item.deptGroupId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="指定审核人" prop="designatedReviewer">
          <user-select :id="form.designatedReviewerArray" ref="userSelectRef" :multiple="true"
                       :org-id="userInfo.orgId" style="width: 100%" @userChange="userChange"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
export default {
  name: "SysMessage"
}
</script>

<script lang="ts" setup>
import {
  addSysMessage,
  delSysMessage,
  getSysMessage,
  listSysMessage,
  updateSysMessage,
  selectPageSysMessage,
  sendOk
} from "@/api/system/sysMessage";

import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user.ts";
import {getOrgDeptGroupByOrgId} from "@/api/system/dept.ts";

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('system_message_type', 'sys_yes_no'))

const {proxy} = getCurrentInstance() as any;
const currentSelectDept = proxy.$currentSelectDept

const formRef = ref();
const quillEditorRef = ref();
const queryParamsRef = ref()
const sysMessageList = ref([]);
const orgDeptGroupList = ref<any>([])
const open = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  orgId: userInfo.orgId,
  sysMessageType: "",
  sysMessageTypeName: "",
  messageContent: "",
  isSendOk: "",
  designatedReviewer: "",
  designatedReviewerName: "",
  designatedReviewDept: "",
  designatedReviewDeptName: "",
  createByName: "",
  updateByName: "",
  messageTitle: ""
})

const form = ref<any>({
  orgId: queryParams.value.orgId,
  sysMessageId: "",
  sysMessageType: "1",
  sysMessageTypeName: "",
  messageContent: "",
  isSendOk: "N",
  designatedReviewer: "",
  designatedReviewerName: "",
  designatedReviewDept: "",
  designatedReviewDeptName: "",
  createByName: "",
  updateByName: "",
  messageTitle: ""
})

const rules = ref({
  sysMessageId: [
    {
      required: true, message: "系统消息主键不能为空", trigger: "blur"
    }
  ],
  sysMessageType: [
    {
      required: true, message: "系统消息类型不能为空", trigger: "change"
    }
  ],
  sysMessageTypeName: [
    {
      required: true, message: "系统消息类型名称不能为空", trigger: "blur"
    }
  ],
  messageContent: [
    {
      required: true, message: "消息内容不能为空", trigger: "blur"
    }
  ],
  isSendOk: [
    {
      required: true, message: "是否发布不能为空", trigger: "blur"
    }
  ],
})

/** 查询系统消息字典列表 */
function getList() {
  selectPageSysMessage(queryParams.value).then((response: any) => {
    sysMessageList.value = response.rows;
    total.value = response.total;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    sysMessageId: "",
    sysMessageType: "1",
    sysMessageTypeName: "",
    messageContent: "",
    isSendOk: "N",
    designatedReviewer: "",
    designatedReviewerName: "",
    designatedReviewDept: "",
    designatedReviewDeptName: "",
    messageTitle: "",
    orgId: queryParams.value.orgId
  }

  nextTick(() => {
    formRef.value.resetFields()
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  // proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.sysMessageId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择机构")
  }
  open.value = true;
  reset();
  title.value = "添加消息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  open.value = true;
  reset();
  const _sysMessageId = row.sysMessageId || ids.value
  getSysMessage(_sysMessageId).then((response: any) => {
    form.value = response.data;
    if (response.data.designatedReviewer) {
      form.value.designatedReviewerArray = response.data.designatedReviewer.split(",")
    }
    if (response.data.designatedReviewDept) {
      form.value.designatedReviewDeptArray = response.data.designatedReviewDept.split(",")
    }
    quillEditorRef.value.setValueHtml(form.value.messageContent);
    title.value = "修改系统消息";
  });
}

/**
 * 发布
 */
function sendOkFun(row: any) {
  ElMessageBox.confirm('是否确认发布？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    sendOk(row.sysMessageId).then(() => {
      getList();
      ElMessage.success("发布成功")
    });
  }).catch(() => {
  })
}

/**
 * 获取消息内容
 * @param html
 */
function messageContentChange(html: any) {
  // form.value.messageContent = html;
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      ElMessageBox.confirm('确定要保存吗？',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        const html = quillEditorRef.value.contentChange();
        form.value.messageContent = encodeURIComponent(html);
        if (form.value.sysMessageId) {
          updateSysMessage(form.value).then(() => {
            ElMessage.success("修改成功");
            open.value = false;
            getList();
          }).finally(() => {
          });
        } else {
          addSysMessage(form.value).then(() => {
            ElMessage.success("新增成功");
            open.value = false;
            getList();
          }).finally(() => {
          });
        }
      }).catch(() => {
      })
    }
  });
}

function orgDeptGroupChange(valueArray: any) {
  let deptGroupNameStr = ""
  valueArray.forEach((value: String) => {
    let index = orgDeptGroupList.value.findIndex((item: any) => {
      return value === item.deptGroupId
    })
    if (index > -1) {
      deptGroupNameStr += orgDeptGroupList.value[index].deptGroupName + ","
    }
  })
  form.value.designatedReviewDept = valueArray.join(',');
  form.value.designatedReviewDeptArray = valueArray;
  form.value.designatedReviewDeptName = deptGroupNameStr.substring(0, deptGroupNameStr.length - 1);
}

/** 用户点击事件 */
function userChange(obj) {
  if (!obj) {
    form.value.designatedReviewer = "";
  } else {
    if (Array.isArray(obj)) {
      form.value.designatedReviewerArray = obj.map(item => item.userId);
      form.value.designatedReviewer = obj.map(item => item.userId).join(',');
      form.value.designatedReviewerName = obj.map(item => item.nickName).join(',');
    }
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _sysMessageIds = row.sysMessageId ||
    ids.value;
  ElMessageBox.confirm('是否确认删除系统消息？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delSysMessage(_sysMessageIds).then(() => {
      getList();
      ElMessage.success("删除成功");
    })
  }).catch(() => {
  })
}

function getOrgDeptGroupByOrgIdFun() {
  getOrgDeptGroupByOrgId(queryParams.value.orgId).then((res: any) => {
    orgDeptGroupList.value = res.data;
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/sysMessage/export', {
    ...queryParams.value
  }, `sysMessage_${new Date().getTime()}.xlsx`)
}

getOrgDeptGroupByOrgIdFun()
getList();
</script>
